package handler

import (
	"git.huoys.com/block_chain/mall/internal/auth/service"
	userApi "git.huoys.com/block_chain/mall/internal/user/api"
	"github.com/gin-gonic/gin"
	"net/http"
)

type AuthHandler interface {
	Login(g *gin.Context)
	UpdateToken(g *gin.Context)
	Register(g *gin.Context)
}

type authHandler struct {
	service service.AuthService
}

func NewCommentHandler(s service.AuthService) AuthHandler {
	return &authHandler{
		service: s,
	}
}

func (h authHandler) Login(g *gin.Context) {
	req := &userApi.LoginReq{}
	if err := g.ShouldBindJSON(req); err != nil {
		g.JSON(http.StatusBadRequest, gin.H{
			"code": http.StatusBadRequest,
			"msg":  err.Error(),
		})
		return
	}
	reply, err := h.service.Login(req.GetPhone(), req.GetPwd(), req.GetDevice())
	if err != nil {
		g.JSON(http.StatusInternalServerError, gin.H{
			"code": http.StatusInternalServerError,
			"msg":  err.Error(),
		})
		return
	}
	g.JSON(http.StatusOK, reply)
	return
}

func (h authHandler) UpdateToken(g *gin.Context) {

	req := &userApi.Token{}

	if err := g.ShouldBindJSON(req); err != nil {
		g.JSON(http.StatusBadRequest, gin.H{
			"code": http.StatusBadRequest,
			"msg":  err.Error(),
		})
		return
	}

	token, err := h.service.UpdateToken(req.Token)
	if err != nil {
		g.JSON(http.StatusInternalServerError, gin.H{
			"code": http.StatusInternalServerError,
			"msg":  err.Error(),
		})
		return
	}

	resp := &userApi.Token{
		Token: token,
	}

	g.JSON(http.StatusOK, resp)

	return
}

func (h authHandler) Register(g *gin.Context) {
	req := &userApi.CreateUserReq{}
	if err := g.ShouldBindJSON(req); err != nil {
		g.JSON(http.StatusBadRequest, gin.H{
			"code": http.StatusBadRequest,
			"msg":  err.Error(),
		})
		return
	}
	err := h.service.Register(req.GetPhone(), req.GetPhoneArea(), req.GetLanguage(), req.GetPwd())
	if err != nil {
		g.JSON(http.StatusInternalServerError, gin.H{
			"code": http.StatusInternalServerError,
			"msg":  err.Error(),
		})
		return
	}
	g.JSON(http.StatusOK, nil)
	return
}
